'use client';

import { useState, useEffect } from 'react';
import { useTheme } from 'next-themes';
import { Sun, Moon, Monitor, Palette, Zap } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

interface ThemeToggleProps {
  className?: string;
  variant?: 'default' | 'animated' | 'minimal' | 'colorful' | 'floating';
  size?: 'sm' | 'md' | 'lg';
  showLabel?: boolean;
}

/**
 * 主题切换组件
 * 支持多种样式和动画效果
 */
export function ThemeToggle({
  className,
  variant = 'default',
  size = 'md',
  showLabel = false,
}: ThemeToggleProps) {
  const { theme, setTheme, resolvedTheme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return (
      <Button
        variant="ghost"
        size={size}
        className={cn('w-9 h-9', className)}
        disabled
      >
        <div className="w-4 h-4 bg-gray-300 rounded animate-pulse" />
      </Button>
    );
  }

  const handleThemeChange = () => {
    setIsAnimating(true);

    // 添加页面过渡动画
    if (variant === 'animated') {
      document.documentElement.style.setProperty(
        '--theme-transition',
        'all 0.3s ease-in-out'
      );

      // 创建遮罩动画
      const overlay = document.createElement('div');
      overlay.className = 'fixed inset-0 z-[9999] pointer-events-none';
      overlay.style.background =
        resolvedTheme === 'dark'
          ? 'radial-gradient(circle at center, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.8) 100%)'
          : 'radial-gradient(circle at center, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0.8) 100%)';
      overlay.style.opacity = '0';
      overlay.style.transition = 'opacity 0.3s ease-in-out';

      document.body.appendChild(overlay);

      // 触发动画
      requestAnimationFrame(() => {
        overlay.style.opacity = '1';

        setTimeout(() => {
          setTheme(resolvedTheme === 'dark' ? 'light' : 'dark');

          setTimeout(() => {
            overlay.style.opacity = '0';
            setTimeout(() => {
              document.body.removeChild(overlay);
              setIsAnimating(false);
            }, 300);
          }, 150);
        }, 150);
      });
    } else {
      setTheme(resolvedTheme === 'dark' ? 'light' : 'dark');
      setTimeout(() => setIsAnimating(false), 300);
    }
  };

  const getSizeClasses = () => {
    switch (size) {
      case 'sm':
        return 'w-8 h-8';
      case 'lg':
        return 'w-12 h-12';
      default:
        return 'w-9 h-9';
    }
  };

  const getIconSize = () => {
    switch (size) {
      case 'sm':
        return 'w-3 h-3';
      case 'lg':
        return 'w-6 h-6';
      default:
        return 'w-4 h-4';
    }
  };

  // 默认样式
  if (variant === 'default') {
    return (
      <Button
        variant="ghost"
        size={size}
        onClick={handleThemeChange}
        className={cn(
          getSizeClasses(),
          'transition-all duration-200 hover:bg-gray-100 dark:hover:bg-gray-800',
          className
        )}
        disabled={isAnimating}
        title={resolvedTheme === 'dark' ? '切换到浅色模式' : '切换到深色模式'}
      >
        <Sun
          className={cn(
            getIconSize(),
            'rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0'
          )}
        />
        <Moon
          className={cn(
            getIconSize(),
            'absolute rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100'
          )}
        />
        <span className="sr-only">切换主题</span>
      </Button>
    );
  }

  // 动画样式
  if (variant === 'animated') {
    return (
      <Button
        variant="ghost"
        size={size}
        onClick={handleThemeChange}
        className={cn(
          getSizeClasses(),
          'relative overflow-hidden transition-all duration-300',
          'hover:bg-gradient-to-r hover:from-orange-100 hover:to-blue-100',
          'dark:hover:from-orange-900/20 dark:hover:to-blue-900/20',
          isAnimating && 'animate-pulse',
          className
        )}
        disabled={isAnimating}
        title={resolvedTheme === 'dark' ? '切换到浅色模式' : '切换到深色模式'}
      >
        {/* 背景动画 */}
        <div
          className={cn(
            'absolute inset-0 transition-all duration-500',
            resolvedTheme === 'dark'
              ? 'bg-gradient-to-br from-blue-500/10 to-purple-500/10'
              : 'bg-gradient-to-br from-orange-500/10 to-yellow-500/10'
          )}
        />

        {/* 图标 */}
        <div className="relative z-10">
          <Sun
            className={cn(
              getIconSize(),
              'transition-all duration-500 text-orange-500',
              resolvedTheme === 'dark'
                ? 'rotate-180 scale-0 opacity-0'
                : 'rotate-0 scale-100 opacity-100'
            )}
          />
          <Moon
            className={cn(
              getIconSize(),
              'absolute inset-0 transition-all duration-500 text-blue-400',
              resolvedTheme === 'dark'
                ? 'rotate-0 scale-100 opacity-100'
                : '-rotate-180 scale-0 opacity-0'
            )}
          />
        </div>

        {/* 光晕效果 */}
        <div
          className={cn(
            'absolute inset-0 rounded-full transition-all duration-300 opacity-0 group-hover:opacity-100',
            resolvedTheme === 'dark'
              ? 'bg-blue-400/20 animate-pulse'
              : 'bg-orange-400/20 animate-pulse'
          )}
        />
      </Button>
    );
  }

  // 最小化样式
  if (variant === 'minimal') {
    return (
      <button
        onClick={handleThemeChange}
        className={cn(
          'p-2 rounded-lg transition-all duration-200',
          'text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100',
          'hover:bg-gray-100 dark:hover:bg-gray-800',
          className
        )}
        disabled={isAnimating}
        title={resolvedTheme === 'dark' ? '切换到浅色模式' : '切换到深色模式'}
      >
        {resolvedTheme === 'dark' ? (
          <Sun className={getIconSize()} />
        ) : (
          <Moon className={getIconSize()} />
        )}
      </button>
    );
  }

  // 彩色样式
  if (variant === 'colorful') {
    return (
      <Button
        variant="ghost"
        size={size}
        onClick={handleThemeChange}
        className={cn(
          getSizeClasses(),
          'relative group transition-all duration-300',
          'hover:scale-110 active:scale-95',
          className
        )}
        disabled={isAnimating}
        title={resolvedTheme === 'dark' ? '切换到浅色模式' : '切换到深色模式'}
      >
        {/* 背景渐变 */}
        <div
          className={cn(
            'absolute inset-0 rounded-full transition-all duration-300 opacity-0 group-hover:opacity-100',
            resolvedTheme === 'dark'
              ? 'bg-gradient-to-r from-blue-500 to-purple-600'
              : 'bg-gradient-to-r from-orange-500 to-yellow-500'
          )}
        />

        {/* 图标容器 */}
        <div
          className={cn(
            'relative z-10 p-1 rounded-full transition-all duration-300',
            resolvedTheme === 'dark'
              ? 'bg-gray-800 text-blue-400'
              : 'bg-white text-orange-500',
            'group-hover:bg-white group-hover:text-white'
          )}
        >
          {resolvedTheme === 'dark' ? (
            <Sun className={cn(getIconSize(), 'animate-spin-slow')} />
          ) : (
            <Moon className={cn(getIconSize(), 'animate-pulse')} />
          )}
        </div>
      </Button>
    );
  }

  // 浮动样式
  if (variant === 'floating') {
    return (
      <div className={cn('fixed bottom-20 right-8 z-40', className)}>
        <Button
          onClick={handleThemeChange}
          className={cn(
            'w-14 h-14 rounded-full shadow-lg hover:shadow-xl transition-all duration-300',
            'bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700',
            'hover:scale-110 active:scale-95',
            isAnimating && 'animate-bounce'
          )}
          disabled={isAnimating}
          title={resolvedTheme === 'dark' ? '切换到浅色模式' : '切换到深色模式'}
        >
          <div className="relative">
            <Sun
              className={cn(
                'w-6 h-6 text-orange-500 transition-all duration-300',
                resolvedTheme === 'dark'
                  ? 'rotate-180 scale-0'
                  : 'rotate-0 scale-100'
              )}
            />
            <Moon
              className={cn(
                'w-6 h-6 text-blue-400 absolute inset-0 transition-all duration-300',
                resolvedTheme === 'dark'
                  ? 'rotate-0 scale-100'
                  : '-rotate-180 scale-0'
              )}
            />
          </div>
        </Button>
      </div>
    );
  }

  return null;
}

/**
 * 主题选择器组件
 * 支持浅色、深色、系统主题选择
 */
interface ThemeSelectorProps {
  className?: string;
  variant?: 'dropdown' | 'tabs' | 'cards';
  showLabels?: boolean;
}

export function ThemeSelector({
  className,
  variant = 'dropdown',
  showLabels = true,
}: ThemeSelectorProps) {
  const { theme, setTheme, themes } = useTheme();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return (
      <div className="w-32 h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" />
    );
  }

  const themeOptions = [
    { value: 'light', label: '浅色', icon: Sun },
    { value: 'dark', label: '深色', icon: Moon },
    { value: 'system', label: '系统', icon: Monitor },
  ];

  // 标签页样式
  if (variant === 'tabs') {
    return (
      <div
        className={cn(
          'flex bg-gray-100 dark:bg-gray-800 rounded-lg p-1',
          className
        )}
      >
        {themeOptions.map(({ value, label, icon: Icon }) => (
          <button
            key={value}
            onClick={() => setTheme(value)}
            className={cn(
              'flex items-center space-x-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200',
              theme === value
                ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 shadow-sm'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100'
            )}
          >
            <Icon className="w-4 h-4" />
            {showLabels && <span>{label}</span>}
          </button>
        ))}
      </div>
    );
  }

  // 卡片样式
  if (variant === 'cards') {
    return (
      <div className={cn('grid grid-cols-3 gap-3', className)}>
        {themeOptions.map(({ value, label, icon: Icon }) => (
          <button
            key={value}
            onClick={() => setTheme(value)}
            className={cn(
              'flex flex-col items-center space-y-2 p-4 rounded-lg border-2 transition-all duration-200',
              theme === value
                ? 'border-blue-500 bg-blue-50 dark:bg-blue-950 text-blue-600 dark:text-blue-400'
                : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 text-gray-600 dark:text-gray-400'
            )}
          >
            <Icon className="w-6 h-6" />
            {showLabels && <span className="text-sm font-medium">{label}</span>}
          </button>
        ))}
      </div>
    );
  }

  // 默认下拉样式
  return (
    <select
      value={theme}
      onChange={e => setTheme(e.target.value)}
      className={cn(
        'px-3 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md',
        'text-gray-900 dark:text-gray-100 text-sm font-medium',
        'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
        'transition-all duration-200',
        className
      )}
    >
      {themeOptions.map(({ value, label }) => (
        <option key={value} value={value}>
          {label}
        </option>
      ))}
    </select>
  );
}

/**
 * 主题预览组件
 * 显示不同主题的预览效果
 */
interface ThemePreviewProps {
  className?: string;
  onThemeSelect?: (theme: string) => void;
}

export function ThemePreview({ className, onThemeSelect }: ThemePreviewProps) {
  const themes = [
    {
      name: 'light',
      label: '浅色主题',
      colors: {
        bg: '#ffffff',
        card: '#f8fafc',
        text: '#1f2937',
        accent: '#3b82f6',
      },
    },
    {
      name: 'dark',
      label: '深色主题',
      colors: {
        bg: '#0f172a',
        card: '#1e293b',
        text: '#f1f5f9',
        accent: '#60a5fa',
      },
    },
  ];

  return (
    <div className={cn('grid grid-cols-1 md:grid-cols-2 gap-4', className)}>
      {themes.map(theme => (
        <button
          key={theme.name}
          onClick={() => onThemeSelect?.(theme.name)}
          className="group relative overflow-hidden rounded-lg border border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 transition-all duration-200"
        >
          {/* 预览区域 */}
          <div
            className="h-32 p-4 transition-transform duration-200 group-hover:scale-105"
            style={{ backgroundColor: theme.colors.bg }}
          >
            {/* 模拟内容 */}
            <div
              className="h-6 w-3/4 rounded mb-2"
              style={{ backgroundColor: theme.colors.card }}
            />
            <div
              className="h-4 w-1/2 rounded mb-3"
              style={{ backgroundColor: theme.colors.card }}
            />
            <div
              className="h-8 w-20 rounded"
              style={{ backgroundColor: theme.colors.accent }}
            />
          </div>

          {/* 标签 */}
          <div className="p-3 bg-gray-50 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700">
            <h3 className="font-medium text-gray-900 dark:text-gray-100">
              {theme.label}
            </h3>
          </div>

          {/* 悬停效果 */}
          <div className="absolute inset-0 bg-blue-500/10 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
        </button>
      ))}
    </div>
  );
}

/**
 * 主题切换Hook
 */
export function useThemeTransition() {
  const { theme, setTheme, resolvedTheme } = useTheme();
  const [isTransitioning, setIsTransitioning] = useState(false);

  const transitionToTheme = (
    newTheme: string,
    options?: {
      duration?: number;
      easing?: string;
      overlay?: boolean;
    }
  ) => {
    const {
      duration = 300,
      easing = 'ease-in-out',
      overlay = true,
    } = options || {};

    setIsTransitioning(true);

    if (overlay) {
      // 创建过渡遮罩
      const overlayEl = document.createElement('div');
      overlayEl.className = 'fixed inset-0 z-[9999] pointer-events-none';
      overlayEl.style.background =
        resolvedTheme === 'dark'
          ? 'radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.9) 100%)'
          : 'radial-gradient(circle, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0.9) 100%)';
      overlayEl.style.opacity = '0';
      overlayEl.style.transition = `opacity ${duration}ms ${easing}`;

      document.body.appendChild(overlayEl);

      requestAnimationFrame(() => {
        overlayEl.style.opacity = '1';

        setTimeout(() => {
          setTheme(newTheme);

          setTimeout(() => {
            overlayEl.style.opacity = '0';
            setTimeout(() => {
              document.body.removeChild(overlayEl);
              setIsTransitioning(false);
            }, duration);
          }, duration / 2);
        }, duration / 2);
      });
    } else {
      setTheme(newTheme);
      setTimeout(() => setIsTransitioning(false), duration);
    }
  };

  return {
    theme,
    resolvedTheme,
    isTransitioning,
    transitionToTheme,
  };
}
